import org.codehaus.groovy.grails.commons.GrailsClassUtils as GCU
import groovy.text.SimpleTemplateEngine
import org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator;
import org.springframework.mock.web.MockServletContext
import org.springframework.core.io.Resource;

/*
 * Usage: grails generate-systemi-all YourDomainClassName
 */

Ant.property(environment:"env")                             
grailsHome = Ant.antProject.properties."env.GRAILS_HOME"    

includeTargets << new File ( "${grailsHome}/scripts/Package.groovy" )
includeTargets << grailsScript("_GrailsBootstrap")          
includeTargets << grailsScript("_GrailsCreateArtifacts")
includeTargets << grailsScript("_GrailsGenerate")


target ('default': "Generates controller and view for a domain class") {
	depends( checkVersion, parseArguments, configureProxy, packageApp, classpath)
	generate()
}

target(generate:"The implementation target") {
	promptForName(type: 'Domain Class')
	def name = argsMap["params"][0]	     
	println "name: $name"
	loadApp()
	configureApp()

 	def domainClass = grailsApp.getClassForName(name) 
	
	if(!domainClass) {
		println "Domain class not found in grails-app/domain."		
		try {
			def config = new GrailsRuntimeConfigurator(grailsApp, appCtx)  
			appCtx = config.configure(appCtx.servletContext)     			
		} catch(Exception e) {
			println e.message
			e.printStackTrace()
		}
		domainClass = grailsApp.getClassForName(name)   
	}
println "domainClass.name ${domainClass.name}"
def domainObject = domainClass.newInstance()    
println "domainObject:"+domainObject.dump()
println "domainObject.COMPOSITE_KEY:"+domainObject.COMPOSITE_KEY

	if(domainClass) {
		def file = new File("src/templates/scaffolding/Controller.groovy")
		def propertyName = name[0].toLowerCase() + name[1..(name.size()-1)]
        println "propertyName: $propertyName"
        def pkg = null
        def pkgPath = null
        def pos = name.lastIndexOf('.')
        if (pos != -1) {
            pkg = name[0..<pos]
            name = name[(pos + 1)..-1]
            propertyName = name[0].toLowerCase() + name[1..(name.size()-1)]
            pkgPath = pkg.replace('.' as char, '/' as char)
            Ant.mkdir(dir: "${basedir}//grails-app/controllers/${pkgPath}")
            pkgPath += '/'
        }
		def binding = [packageName:pkg, className:name, propertyName:propertyName, domainObject:domainObject]
		def writable = new SimpleTemplateEngine().createTemplate(file).make(binding)
        if (pkg) {
            new File("grails-app/controllers/${pkgPath}${name}Controller.groovy").write(writable.toString())
        } else {
		    new File("grails-app/controllers/${name}Controller.groovy").write(writable.toString())
        }
		generateController = false // done manually with the above binding so we could instance an object
		generateForName = argsMap["params"][0]
		generateForOne()
		event("StatusFinal", ["Finished generation of ${name}Controller.groovy and associated views"])
	} else {
		event("StatusFinal", ["No domain class found for name ${name}. Please try again and enter a valid domain class name"])
	}
}
